study = {};
study.social = false;
study.editors = {};

study.ready = function() {
    // select an element by ID, and register an onclick handler
    $("#addset").click(study.renderAddSetForm);
    $("#usageHistoryLink").click(study.displayUsageHistoryPage);
    study.refreshSetList(true);
    $('#searchbtn').click(study.search);
};

study.resubscribe = function(e) {
    e.preventDefault();
    var subscribe_link = $(this).attr('href');
    $(this).parent().html("subscribed");
    $.ajax({'url': subscribe_link, 'type': 'POST', 'success': function() { study.refreshSetList(false); }});
    return false;
};

study.fetchTemplate = function(templateName) {
    if (typeof(study.templates) == 'undefined') {
	study.templates = {};
    }
    if (study.templates[templateName]) {
	return study.templates[templateName];
    }
    var file = '/ajax/' + templateName + '.html';
    $.ajax({'url': file, 'type': 'GET', 'dataType': 'html', 'async': false, 'success': function(html,textStatus){
	    study.templates[templateName] = html;
	    }});
    return study[templateName];
};

study.search = function(e) {
    e.preventDefault();
    var json = $("#search_form input").serializeArray();
    study.removeEditors();
    $("#content").load('/ajax/search.html', json, function(){
	$(".stripeMe tr:nth-child(even)").addClass("alt");
	$(".resubscribe_link").click(study.resubscribe);
	$("a.setlink").click(study.renderSet);
	study.adjustHeight();
    });
    return false;
};

study.displayUsageHistoryPage = function(e) {
    e.preventDefault();
    study.removeEditors();
    $("#content").load('/ajax/usageHistory.html',{},
	    function(){ 
		$(".stripeMe tr:nth-child(even)").addClass("alt");
		$(".resubscribe_link").click(study.resubscribe);
		$("a.setlink").click(study.renderSet);
		study.adjustHeight();
	    }
	);
    return false;
};

study.displayMsg = function(type,msg) {
    if (type == 'error') {
	$('#mesgArea').html('<span class="error">' + msg + '</span>').removeClass('hideMe');
    } else {
	$('#mesgArea').html('<span class="mesg">' + msg + '</span>').removeClass('hideMe');
    }
};

study.renderAddSetForm = function(e) {
    e.preventDefault();
    study.removeEditors();
    $("#content").load('/ajax/addsetform.html',{},function(){
	$("#submit").click(study.submitAddSetForm);
	study.addClickHandlerForSets();
	study.addEditors();
    });
    return false;
};

study.sendFeedback = function(e) {
    e.preventDefault();
    var feedback = study.getEditorContent('feedbackEditor');
    var setKey = $('#hidden_setKey').text();
    var email = $('#email').val();
    var data = {'feedback': feedback, 'setKey': setKey};
    if ((typeof(email) != 'undefined') && (email != '')) {
	data.email = email;
    }
    $.ajax({'url': '/ajax/sendFeedback.json', 'type': 'POST', 'dataType': 'json', 'data': data, 'async': false});
    study.removeEditors();
    $('textarea.loadEditor').remove();
    $(this).val('Feedback sent!').disable();
    var reload = $('<input type="button" value="Display Set"/>');
    reload.click(study.reloadCurrentSet);
    reload.insertAfter(this);
    study.adjustHeight();
    return false;
};

study.sendOurFeedback = function(e) {
    e.preventDefault();
    var ourFeedback = study.getEditorContent('ourFeedback');
    var email = $('#email').val();
    var data = {'ourFeedback': ourFeedback};
    if ((typeof(email) != 'undefined') && (email != '')) {
	data.email = email;
    }
    $.ajax({'url': '/ajax/sendOurFeedback.json', 'type': 'POST', 'dataType': 'json', 'data': data, 'async': false});
    study.removeEditors();
    $('textarea.loadEditor').remove();
    $(this).val('Feedback sent!').disable();
    var reload = $('<input type="button" value="Display Set"/>');
    reload.click(study.reloadCurrentSet);
    reload.insertAfter(this);
    study.adjustHeight();
    return false;
};

study.isLoggedIn = function() {
    if ($('#topmenu').length == 1) {
	return true;
    } else {
	return false;
    }
};
study.displayPage = function(e) {
    e.preventDefault();
    var href = $(this).attr('href');
    study.removeEditors();
    var callback = function() {};
    if (href.search(/Feedback/) >= 0) {
	$('#content').html(study.fetchTemplate('ourFeedback'));
	study.addEditors();
	$('#ourFeedback_sendBtn').click(study.sendOurFeedback);
    } else if (href.search(/faq\.html/) >= 0) {
	$('#content').html(study.fetchTemplate('faq'));
	$(".stripeMe tr:nth-child(even)").addClass("alt");
    } else if (href.search(/tos\.html/) >= 0) {
	$('#content').html(study.fetchTemplate('tos'));
    } else if (href.search(/contact\.html/) >= 0) {
	$('#content').html(study.fetchTemplate('contact'));
    }
    $('#content').find('[href="/ajax/faq.html"]').click(study.displayPage);
    if (study.isLoggedIn()) {
	$('#content').find('[href="/"]').click(study.reloadCurrentSet);
    }
    $('#content').find('[href="/ajax/contact.html"]').click(study.displayPage);
    study.adjustHeight();
    if ($('#topmenu').length == 1) {
	$('#topmenu').scrollIntoView();
    }
    return false;
};

study.submitAddSetForm = function(e) {
    e.preventDefault();
    var selectedIndex = $("#visibility").attr('selectedIndex');
    var sel = $("#visibility").get(0);
    var visibility = sel.options[selectedIndex].value;
    var title = $('#title').val();
    if (title.search(/\S/) == -1) {
	study.error('#title','Title is missing.');
	return false;
    }
    $(this).val('Please wait').disable();
    var materials = study.getEditorContent('materials');
    var description = study.getEditorContent('description');
    var data = {'title': title, 'visibility': visibility, 'materials': materials, 'description': description}
    var em = $('#email');
    if (em.length == 1) {
	var email = em.val();
	if ((typeof(email) != 'undefined') && (email != '')) {
	    data.email = email;
	}
    }
    $.ajax({'url': '/ajax/addset.json', 'type': 'POST', 'dataType': 'json', 'data': data, 'async': false, 'success': function(json,textStatus){
	    study.removeEditors();
	    $('#content').html('');
	    study.refreshSetList(true);
	}
    });
    return false;
};

study.error = function(selector,msg) {
    $('<div class="error">' + msg + '</div>').insertBefore(selector);
};

study.listView_click = function(e) {
    var target = e.target;
    var cell = $(target).parent();
    if ( $(target).hasClass('editbtn') ) {
	study.editEntry(cell);
    } else if ( $(target).hasClass('deletebtn') ) {
	study.deleteEntry_listView(cell);
    }
};

study.renderTagList = function() {
    $('#taglist').html('');
    var tags = study.tags;
    for (var i = 0, j = tags.length; i < j; i++) {
	var t = $('<option></option>');
	t.val(tags[i]);
	t.text(tags[i]);
	t.appendTo('#taglist');
    }
};

study.entriesSearch_listView = function(e) {
    $(this).disable().val('Searching');
    var tag = study.getSelectedValue('#taglist');
    var searchTerm = '';
    var setKey = $('#hidden_setKey').text();
    if ( $('#entries_search').length > 0) { searchTerm = $('#entries_search').val(); }
    var data = {'searchTerm': searchTerm, 'tag': tag, 'setKey': setKey};
    study.adjustHeight();
    $('#thelistContainer').load('/ajax/listViewSearchResultTable.html',data, function() {
	    $("#thelist").click(study.listView_click);
	    $('#thelist').dblclick(study.editEntry_dblclick);
	    var count = $('#thelist').find('td.questionColumn').length;
	    if (count == 0) {
		$('#thelist').hide();
	    }
	    $('#entries_search_result').html('Found: ' + count);
	    $(".stripeMe tr:nth-child(even)").addClass("alt");
	    $('#entries_search_btn').val('Search').enable();
	    study.adjustHeight();
	});
};

study.doNothing_handler = function(e) {
    e.preventDefault();
    return false;
};

study.renderTemplate = function(templateName,id) {
    var html = study.fetchTemplate(templateName);
    $('#' + id).html(html);
    study.adjustHeight();
};

study.addTag = function(e) {
    e.preventDefault();
    $('#newTag_btn').attr('value','Processing').disable();
    var setKey = $('#hidden_setKey').text();
    var newTag = $('#newTag_input').val();
    if ((newTag == undefined) || (newTag.search(/\S/) == -1)) {
	$('#newTag_btn').enable().val('Add Tag');
	return false;
    }
    var data = {'setKey': setKey, 'tag': newTag };
    $.ajax({'url': '/ajax/addTag.json', 'type': 'POST', 'dataType': 'json', 'async': false, 'data': data, 'success': function(json,textStatus) {
		var tag = $('#newTag_input').val();
		var node = $('<tr><td class="tagTable"><input type="checkbox" name="tag" class="tag_input" value="' + tag + '"/><span class="draggable">' + tag + '</span></td></tr>');
		node.find('.draggable').draggable();
		node.insertBefore('#newTag_tr');
		node.find('.tag_input').click();
		$('#newTag_input').val('');
		$('#newTag_btn').val('Add Tag').enable();
		study.tags = json.tags;
		study.renderTagList();
		study.adjustHeight();
	    }
	});
    return false;
};


study.deleteTag = function(draggable) {
    var tag = draggable.text();
    draggable.parent().remove();
    var setKey = $('#hidden_setKey').text();
    var data = {'setKey': setKey, 'tag': tag };
    $.ajax({'url': '/ajax/deleteTag.json', 'type': 'POST', 'dataType': 'json', 'data': data, 'async': false, 'success': function(json,textStatus){
	    study.tags = json.tags;
	    study.renderTagList();
	    study.adjustHeight();
	}});
};

study.renderTagTable = function(tags_json) {
    $('#tagTableDiv').html('');
    var node = $('<table></table');
    var tags = study.tags;
    for (var i = 0, j = tags.length; i < j; i++) {
	var tag = tags[i];
	if ((tag != "") && (tag != '-')) {
	    node.append('<tr><td class="tagTable"><input type="checkbox" name="tag" class="tag_input" value="' + tag + '"/><span class="draggable">' + tag + '</span></td></tr>');
	}
    }
    node.append('<tr id="newTag_tr"><td><input type="text" id="newTag_input"/><input type="button" id="newTag_btn" value="Add Tag"/><span id="tag_delete">Drag and drop tag here to delete.</span></td></tr>');
    node.appendTo('#tagTableDiv');
    $('#newTag_btn').click(study.addTag);
    if (typeof(tags_json) != 'undefined') {
	var nodes = $('#tagTableDiv').find('.tag_input');
	for(var i = 0, j = nodes.length; i < j; i++) {
	    node = $(nodes.get(i));
	    var tag = node.val();
	    if (tags_json[tag]) {
		node.click();
	    }
	}
    }
    study.adjustHeight();
    $('#tagTableDiv').find('.draggable').draggable();
    $('#tag_delete').droppable(
	    {
	    accept: '.draggable',
	    over: function(event,ui) { $(this).addClass('droppableOver'); },
	    drop: function(event,ui) { study.deleteTag(ui.draggable); $(this).removeClass('droppableOver'); },
	    out: function(event,ui) { $(this).removeClass('droppableOver'); }
	    }
	    );
};

study.removeContentOfOtherTabs = function() {
    var map = {};
    map['List View'] = 'listViewContainerDiv';
    map['Study View'] = 'studyViewContainerDiv';
    map['Unsubscribe'] = 'unsubscribeContainerDiv';
    map['Subscribe'] = 'subscribeContainerDiv';
    map['Feedback / Contact'] = 'feedbackContainerDiv';
    map['Study Materials'] = 'studyMaterialsContainerDiv';
    map['Edit'] = 'editTabContainer';
    map['Contributors'] = 'contributorsContainerDiv';
    for (t in map) {
	if (t != study.tabName) {
	    var id = map[t];
	    $('#' + id).html('');
	}
    }
};

study.renderTabs = function(json,text) {
    $('#content').html(json.renderSetHTML);
    study.adjustHeight();
    study.tags = json.tags;
    if ((study.social) && (study.socialView != 'canvas')) {
	$('ul.tabs').find('span').each(function() {
	    if ( $(this).text() != 'Study View') {
		$(this).parent().parent().remove();
	    }
	});
    }
    study.tabs = $("#settabs").tabs({'collapsible': true, 'deselectable': true});
    $('#settabs').block({'css': {'backgroundColor': 'transparent'}, 'message': null, 'overlayCSS': {'opacity': 0}}); 
    $('.ui-tabs-nav').bind('tabsselect', function(event,ui) {
	    study.tabName = '';
	    study.removeEditors();
	    study.removeContentOfOtherTabs();
	    $('#settabs').block({'css': {'background-color': 'transparent'}, 'message': null, 'overlayCSS': {'opacity': 0}}); 
	});
    $('.ui-tabs-nav').bind('tabsshow', function(event,ui) {
	    $('#settabs').unblock();
	    var tabName = ui.tab.text;
	    study.tabName = tabName;
	    study.tabIndex = ui.index;
	    study.uiPanel = ui.panel; // element that contains the content of the tab
	    study.uiTab = ui.tab; // anchor element of the clicked tab
	    study.removeContentOfOtherTabs();
	    if ((! study.social) || (study.socialView == 'canvas')) {
	        if ($('#footer').hasClass('hideMe')) {
		    $('#footer').removeClass('hideMe');
		    $('.footer').click(study.displayPage);
		}
	    }
	    var setKey = $('#hidden_setKey').text();
	    study.adjustHeight();
	    if (tabName == "List View") {
		$(".stripeMe tr").mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
		$(".stripeMe tr:nth-child(even)").addClass("alt");
		$("#thelist").click(study.listView_click);
		var count = $('#thelist').find('td.questionColumn').length;
		if (count == 0) {
		    $('#thelist').hide();
		}
		if ($('#addEntryDiv').children().length > 0) {
		    // quick hack.  If we are supposed to show the add entry div, show it completely with the tag table as well
		    study.showAddEntryDiv_listView();
		}
		study.entryCount = parseInt($('#entryCount_all').text());
		study.showOrHideEntryCount();
		$('#thelist').dblclick(study.editEntry_dblclick);
		$('#entries_search_form').submit(study.doNothing_handler);
		$('#entries_search_table').removeClass('hideMe');
		$('#entries_search_btn').click(study.entriesSearch_listView);
	    } else if (tabName == "Unsubscribe") {
	        $('a', ui.panel).click(function(e) {
		    e.preventDefault();
		    var url = $(this).attr('href');
		    $(ui.panel).load(url);
		    return false;
		});
	    } else if (tabName == "Study View") {
		$('#entries_search_form').submit(study.doNothing_handler);
		$('#entries_search_table').removeClass('hideMe');
		$('#studyViewContainerDiv').removeClass('hideMe');
		$('#start').click(study.startStudy);
		if (study.social) {
		    if (study.socialView != 'canvas') {
			$('#settabs').remove();
			$('#start').click();
		    }
		}
	    } else if (tabName == "Share") {
		$('.facebookShareLink').click(study.shareOnFacebook_click);
		study.shareOnFacebook();
	    } else if (tabName == "Feedback / Contact") {
		study.addEditors();
		$('#feedback_sendBtn').click(study.sendFeedback);
	    } else if (tabName == 'Contributors') {
		$('#contributor_search_btn').click(study.contributorSearch);
		$('#remove_contributors_btn').click(study.removeContributors);
	    } else if (tabName == "Edit") {
		study.addEditors();
		$("#submit").click(study.submitEditSetForm);
	    }
	    study.adjustHeight();
	});
};

study.reloadCurrentTab = function(callback) {
    /*
    var t = study.tabs;
    t.tabs('load',study.tabIndex);
    */
    // var href = $('.ui-tabs-selected').find('a').attr('href');
    var href = $.data(study.uiTab, 'load.tabs');
    $(study.uiPanel).load(href,{},callback);
    // $('.ui-tabs-selected').find('a').click();
};

study.removeContributors = function(e) {
    e.preventDefault();
    var setKey = $('#hidden_setKey').text();
    var ar = $(this.form).find('input:checked').serializeArray();
    ar.push({'name': 'setKey', 'value': setKey});
    $.ajax({'url': '/ajax/removeContributors.json',
	    'type': 'POST',
	    'dataType': 'json',
	    'async': false,
	    'data': ar,
	    'success': function() {
	            study.reloadCurrentTab(function(){
			$('#contributor_search_btn').click(study.contributorSearch);
			$('#remove_contributors_btn').click(study.removeContributors);
			study.adjustHeight();
		    });
		}
	    });
    return false;
};

study.addContributors = function(e) {
    e.preventDefault();
    var setKey = $('#hidden_setKey').text();
    var ar = $('#contributorSearchResult').find('input:checked').serializeArray();
    ar.push({'name': 'setKey', 'value': setKey});
    $.ajax({'url': '/ajax/addContributors.json',
	    'type': 'POST', 
	    'dataType': 'json',
	    'async': false,
	    'data': ar,
	    'success': function() {
	            study.reloadCurrentTab(function(){
			$('#contributor_search_btn').click(study.contributorSearch);
			$('#remove_contributors_btn').click(study.removeContributors);
			study.adjustHeight();
		    });
		}
	    });
    return false;
};

study.contributorSearch_displayResult = function(data) {
    if (data.users.length > 0) {
	var r = $('<table></table>');
	for (var i = 0, j = data.users.length; i < j; i++) {
	    r.append('<tr><td>' + data.users[i].displayName + '</td><td><input type="checkbox" name="contributor" value="' + data.users[i].key + '"/></td></tr>');
	}
	r.append('<tr><td colspan="2"><input type="button" id="contributor_add_btn" value="Allow selected users to contribute."/></td></tr>');
	r.find('#contributor_add_btn').click(study.addContributors);
	$('#contributorSearchResult').html('<form action="/" method="post" id="contributorSearchResultForm"></form>');
	r.appendTo('#contributorSearchResultForm');
    } else {
	$('#contributorSearchResult').html('<p>We did not find any user with the name or email address you specified.</p>');
    }
    $('#contributor_search_btn').val('Search').enable();
    study.adjustHeight();
};

study.contributorSearch = function(e) {
    e.preventDefault();
    var nameOrEmail = $('#nameOrEmail').val();
    var setKey = $('#hidden_setKey').text();
    $(this).val('Please wait!').disable();
    $.ajax({'url': '/ajax/contributorSearch.json',
	    'type': 'POST', 
	    'dataType': 'json',
	    'async': false,
	    'data': {'setKey': setKey, 'nameOrEmail': nameOrEmail},
	    'success': study.contributorSearch_displayResult
	    });
    return false;
};

study.getSelectedValue = function(selector) {
    var selectedIndex = $(selector).attr('selectedIndex');
    var sel = $(selector).get(0);
    var val = sel.options[selectedIndex].value;
    return val;
};

study.getSelectedOption = function(selector) {
    var selectedIndex = $(selector).attr('selectedIndex');
    var sel = $(selector).get(0);
    var selectedOption = sel.options[selectedIndex];
    return $(selectedOption);
};

study.startStudy = function(e) {
    e.preventDefault();
    var tag = study.getSelectedValue('#taglist');
    var setKey = $('#hidden_setKey').text();
    $(this).val('Please wait!').disable();

    $.ajax({'url': '/ajax/study.json',
	    'type': 'POST', 
	    'dataType': 'json',
	    'async': false,
	    'data': {'setKey': setKey, 'tag': tag},
	    'success': study.renderSetEntries
	    });
    return false;
};

study.setlistUp = function(e) {
    e.preventDefault();
    $('#setlist_select').blur();
    $('#setlist_select').change();
    return false;
};

study.setlistChange = function(e) {
    e.preventDefault();
    var value = study.getSelectedValue('#setlist_select');
    $('#hidden_setKey').text(value);
    study.removeEditors();
    $.ajax({'url': '/ajax/renderSet.json', 'dataType': 'json', 'data': {'setKey': value}, 'success': study.renderTabs});
    $('.setlist_currentlySelected').unbind('mouseup').removeClass('.setlist_currentlySelected');
    var option = study.getSelectedOption('#setlist_select');
    option.mouseup(study.setlistUp).addClass('setlist_currentlySelected');
    return false;
};

study.reloadCurrentSet = function(e) {
    e.preventDefault();
    var value = $('#hidden_setKey').text();
    study.removeEditors();
    $.ajax({'url': '/ajax/renderSet.json', 'dataType': 'json', 'data': {'setKey': value}, 'success': study.renderTabs});
    return false;
};

study.log = function(msg) {
    if (typeof(window.console) != 'undefined') {
	console.log(msg);
    }
};

study.renderSetList = function(data,loadCurrentSet) {
    var list = data.list;
    var len = list.length;
    var html = "";
    for (i = 0; i < len; i++) {
	var k = list[i][0];
	var title = list[i][1];
	var current = list[i][2];
	html = html + "<option class='setlist_option' value='" + k + "'";
	if (current == 1) {
	    html = html + " selected='selected'";
	}
	html = html + ">" + title + "</option>";
    }
    if (html != "") {
	html = '<form class="setlist" action="/" method="post"><select id="setlist_select">' + html + '</select></form>';
	$('div.setlist').html(html);
	$('#setlist_select').change(study.setlistChange);
	if (loadCurrentSet) {
	    var value = study.getSelectedValue('#setlist_select');
	    $('#hidden_setKey').text(value);
	    study.removeEditors();
	    study.renderTabs(data);
	    $('.setlist_currentlySelected').unbind('mouseup').removeClass('.setlist_currentlySelected');
	    var option = study.getSelectedOption('#setlist_select');
	    option.mouseup(study.setlistUp).addClass('setlist_currentlySelected');
	}
    } else if ((study.social) && (study.socialView != 'canvas')) {
    } else {
	study.removeEditors();
	$('#content').html('<p class="clear">If this is your first time using this application, we recommend that you use the search box above (just click the "Search" button) to study existing set created by other users.  If you do not find a set for which you want to study, you can create a new set and share it with other.  The link to create a new set is on the top right corner of the screen.  Enjoy our service.  Lets us know if you have any problems, suggestions, etc.</p>');
	if ($('#footer').hasClass('hideMe')) {
	    $('#footer').removeClass('hideMe');
	    $('.footer').click(study.displayPage);
	}
    }
};

study.refreshSetList = function(loadCurrentSet) {
    $.getJSON('/ajax/getsetlist.json',{},function(data) {
	study.renderSetList(data,loadCurrentSet);
    });
};

study.editEntry_cancel = function(question,answer,entryKey,setKey) {
    // we must not use the content of editors becaue they may have been modified
    study.removeEditors();
    $('.entry_edit').html(study.fetchTemplate('listViewRowTemplate_contributor'));
    $('.entry_edit').find('.questionColumn').html(question);
    $('.entry_edit').find('.answerColumn').html(answer);
    $('.entry_edit').find('.contributorColumn').find('.entryKey').text(entryKey);
    $('.entry_edit').scrollIntoView();
    $('.entry_edit').removeClass('entry_edit');
    study.editEntry_showOtherControls();
};

study.editEntry_hideOtherControls = function() {
    study.hideAddEntryDiv_listView();
    $('.editbtn').hide();
};

study.hideAddEntryDiv_listView = function() {
    study.removeEditors();
    study.addEntry_saveSelectedTagsFromDOM();
    $('#addEntryDiv').html('');
}

study.addEntry_saveSelectedTagsFromDOM = function() {
    var tagNodes = $('#addEntryDiv').find('.tag_input');
    var tags = {};
    for (var i = 0, j = tagNodes.length; i < j; i++) {
	var node = $(tagNodes.get(i));
	var checked = node.attr('checked');
	if (checked) {
	    var v = node.attr('value');
	    tags[v] = true;
	}
    }
    study.addEntry_selectedTags_json = tags;
};

study.editEntry_showOtherControls = function() {
    study.showAddEntryDiv_listView();
    $('.editbtn').show();
    study.adjustHeight();
};

study.editEntry_dblclick = function(e) {
    e.preventDefault();
    var cell = $(e.target);
    while (cell.parent().parent().parent().attr('id') != 'thelist') {
	cell = cell.parent();
    }
    var row = cell.parent();
    var children = row.children();
    cell = $(children[2]);
    study.editEntry(cell);
    return false;
};

study.splitQueryArguments = function(str) {
    var result = {};
    str = str.replace(/.*?\?/,''); // remove everything before the ?
    str = str.replace(/#.*/,''); // remove the fragment, so what is left is just the query string
    var parts = str.split(/[&;]/);
    for (var i = 0, j = parts.length; i < j; i++) {
	var part = parts[i];
	var kv = part.split(/=/);
	result[kv[0]] = kv[1];
    }
    return result;
};

study.editEntry = function(cell) {
    if ( $('.entry_edit').length > 0 ) {
	return false;
    }

    study.editEntry_hideOtherControls();
    var question = cell.prev().prev().html();
    var answer = cell.prev().html();
    var entryKey = cell.find('.entryKey').text();
    var setKey = $('#hidden_setKey').text();
    var row = cell.parent();
    row.addClass('entry_edit');
    row.html('<td colspan="3"><div id="editEntryDiv"></div></td>');
    var newCell = row.find('div');
    var data = {'entryKey': entryKey, 'setKey': setKey};
    $.ajax({'url': '/ajax/getEntry.json', 'type': 'POST', 'dataType': 'json', 'data': data,
	    'success': function(json,textStatus){
		newCell.html(study.fetchTemplate('editEntryTemplate'));
		newCell.find('.entryKey').val(entryKey);
		study.renderTagTable(json.tags_json);
		$('#question').val(question);
		$('#answer').val(answer);
		study.addEditors();

		$('.cancelbtn').click(function() { study.editEntry_cancel(question,answer,entryKey,setKey); });
		$('.savebtn').click(function() { study.editEntry_save(entryKey,setKey); });
		$('.entry_edit').scrollIntoView();
	    }});

}

study.editEntry_studyView = function(e) {
    e.preventDefault();
    study.hideAddEntryDiv_studyView();
    var entryKey = $('#hidden_entryKey').text();
    var setKey = $('#hidden_setKey').text();
    var editEntryDiv = $('#editEntryDiv');
    editEntryDiv.html(study.fetchTemplate('editEntryTemplate'));
    editEntryDiv.find('.entryKey').val(entryKey);
    var data = {'entryKey': entryKey, 'setKey': setKey};
    $.ajax({'url': '/ajax/getEntry.json', 'type': 'POST', 'dataType': 'json', 'data': data,
	    'success': function(json,textStatus){
		var question = json.q;
		var answer = json.a;
		$('#question').val(json.q);
		$('#answer').val(json.a);
		study.addEditors();
		study.renderTagTable(json.tags_json);
		study.adjustHeight();

		$('.cancelbtn').click(function() { 
		    study.removeEditors();
		    $('#editEntryDiv').html(''); 
		    study.adjustHeight();
		    });
		$('.savebtn').click(study.editEntry_studyView_save);
	    }});
    return false;
};

study.editEntry_studyView_save = function(e) {
    e.preventDefault();
    var entryKey = $('#hidden_entryKey').text();
    var setKey = $('#hidden_setKey').text();
    var question = study.getEditorContent('question');
    var answer = study.getEditorContent('answer');
    var tags = study.getSelectedTagsFromDOM();
    var data = {'question': question, 'answer': answer, 'entryKey': entryKey, 'setKey': setKey, 'tags': tags };
    study.removeEditors();
    $.ajax({'url': '/ajax/updateentry.json', 'type': 'POST', 'dataType': 'json', 'data': data});
    $('#study_question_div').html(question);
    $('#study_answer_div').html(answer);
    $('#editEntryDiv').html('');
    study.adjustHeight();
    return false;
};

study.getSelectedTagsFromDOM = function() {
    var tagNodes = $('#tagTableDiv').find('.tag_input');
    var tags = ['-'];
    for (var i = 0, j = tagNodes.length; i < j; i++) {
	var node = $(tagNodes.get(i));
	var checked = node.attr('checked');
	if (checked) {
	    tags.push(node.attr('value'));
	}
    }
    return tags;
};

study.editEntry_save = function(entryKey,setKey) {
    var question = study.getEditorContent('question');
    var answer = study.getEditorContent('answer');
    var tags = study.getSelectedTagsFromDOM();
    study.removeEditors();
    var data = {'question': question, 'answer': answer, 'entryKey': entryKey, 'setKey': setKey, 'tags': tags };
    $.ajax({'url': '/ajax/updateentry.json', 'type': 'POST', 'dataType': 'json', 'data': data});
    $('.entry_edit').html(study.fetchTemplate('listViewRowTemplate_contributor'));
    $('.entry_edit').find('.questionColumn').html(question);
    $('.entry_edit').find('.answerColumn').html(answer);
    $('.entry_edit').find('.contributorColumn').find('.entryKey').text(entryKey);
    study.editEntry_showOtherControls();
    study.adjustHeight();
    $('.entry_edit').scrollIntoView();
    $('.entry_edit').removeClass('entry_edit').mouseover();
};

study.addEditors = function() {
    var c = $('textarea.loadEditor');
    for (var i = 0, j = c.length; i < j; i++) {
	var id = $(c.get(i)).attr('id');
	study.editors[id] = true;
    }
    tinyMCE.init(study.tinyMCESettings);
    study.adjustHeight();
};

study.removeEditors = function() {
    var c = $('textarea.loadEditor');
    for (var i = 0, j = c.length; i < j; i++) {
	var id = $(c.get(i)).attr('id');
	var p = $(c.get(i)).parent();
	p.hide();
	var editor = tinyMCE.getInstanceById(id);
	if (editor) {
	    editor.setContent('');
	    $(id).hide();
	    if (editor) editor.remove();
	    $(id).show();
	    p.show();
	}
    }
    study.adjustHeight();
};

study.deleteEntry_listView = function(cell) {
    var entryKey = cell.find('.entryKey').text();
    study.hideAddEntryDiv_listView();
    $.ajax({'url': '/ajax/deleteentry.json', 'type': 'POST', 'dataType': 'json', data: {'entryKey': entryKey}, 'success': study.showAddEntryDiv_listView});
    cell.parent().remove();
    if ($('#thelist').find('td.questionColumn').length == 0) {
	$('#thelist').hide();
    }
    study.entryCount = study.entryCount - 1;
    study.showOrHideEntryCount();
    study.adjustHeight();
    return false;
}

study.addClickHandlerForSets = function() {
    $("a.addset_setlist_link").click(study.renderSet);
};

study.renderSet = function(e) {
    e.preventDefault();
    var href = $(this).attr('href');
    var parameters = study.splitQueryArguments(href);
    var setKey = parameters['setKey'];
    $('#hidden_setKey').text(setKey);
    study.removeEditors();
    $.ajax({'url': '/ajax/renderSet.json', 'dataType': 'json', 'data': {'setKey': value}, 'success': study.renderTabs});
    return false;
};

study.getEditorContent = function(id) {
    var editor = tinyMCE.getInstanceById(id);
    return editor.getContent();
};

study.setEditorContent = function(id,content) {
    var editor = tinyMCE.getInstanceById(id);
    editor.setContent(content);
};

study.submitEditSetForm = function(e) {
    e.preventDefault();
    var setKey = $("#setKey").attr('value');
    var title = $("#title").attr('value');
    var selectedIndex = $("#visibility").attr('selectedIndex');
    var sel = $("#visibility").get(0);
    var visibility = sel.options[selectedIndex].value;
    var materials = study.getEditorContent('materials');
    var description = study.getEditorContent('description');
    var data = {'title': title, 'visibility': visibility, 'setKey': setKey, 'materials': materials, 'description': description};
    var em = $('#email');
    if (em.length == 1) {
	var email = em.val();
	if ((typeof(email) != 'undefined') && (email != '')) {
	    data.email = email;
	}
    }
    $.ajax({'url': '/ajax/saveSet.json', 'type': 'POST', 'dataType': 'json', 'data': data, 'async': false});
    $('table.edit_set > tbody > tr').hide();
    $(this).val('Save!').disable();
    var reload = $('<input type="button" value="Display Set"/>');
    reload.click(study.reloadCurrentSet);
    reload.insertAfter(this);
    $(this).parent().parent().show();
    study.adjustHeight();
    return false;
};

study.showAddEntryDiv_listView = function() {
    $('#addEntryDiv').html(study.fetchTemplate('addEntryTemplate'));
    $('#addEntryDiv').show();
    study.addEditors();
    study.renderTagTable(study.addEntry_selectedTags_json);
    study.adjustHeight();
    $("input.submitbtn").click(study.addEntry_listView);
}

study.addEntry_listView_success = function(json, textStatus) {
    var newRow = $('<tr></tr>');
    newRow.html(study.fetchTemplate('listViewRowTemplate_contributor'));
    newRow.find('.questionColumn').html(json.question);
    newRow.find('.answerColumn').html(json.answer);
    newRow.find('.contributorColumn').find('.entryKey').text(json.entryKey);
    newRow.appendTo('#thelist');
    var rowCount = $('#thelist').find('td.questionColumn').length;
    if (rowCount == 1) {
	// show the table if it was previously hidden
	$('#thelist').show();
    }
    newRow.scrollIntoView();

    newRow.mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
    $(".stripeMe tr").removeClass('alt');
    $(".stripeMe tr:nth-child(even)").addClass("alt");
    $('.submitbtn').val('Add').enable();
    study.setEditorContent('question','');
    study.setEditorContent('answer','');
    study.adjustHeight();
    newRow.scrollIntoView();
    study.entryCount = study.entryCount + 1;
    study.showOrHideEntryCount();
};

study.renderEntry = function() {
    var currentEntry = study.set_json.currentEntry;
    var d = study.set_json.entries[currentEntry];
    d.view = 'study';
    d.shown = d.shown + 1;
    $('#study_status').text((currentEntry + 1) + ' / ' + study.set_json.entries.length); 
    $.ajax({'url': '/ajax/getEntry.json', 'type': 'POST', 'dataType': 'json', 'data': d, 'success': function(json,textStatus){
	    d.q = json.q;
	    d.a = json.a;
	    d.tags = json.tags;
	    d.tags_json = json.tags_json;
	    $('#studyViewContainerDiv').find('.study_hideMe').addClass('hideMe');
	    $('#studyViewContainerDiv').find('#study_question_div').html(json.q);
	    $('#studyViewContainerDiv').find('#study_answer_div').html(json.a);
	    $('#studyViewContainerDiv').find('#hidden_entryKey').text(d.entryKey);
	    $('#studyViewContainerDiv').removeClass('hideMe');
	    study.adjustHeight();
	}
    });
};

study.adjustHeight = function() {
    if (study.social) {
	gadgets.window.adjustHeight();
    }
};

study.renderNextEntry = function(e) {
    e.preventDefault();
    study.set_json.currentEntry += 1;
    if (study.set_json.currentEntry == study.set_json.entries.length) study.set_json.currentEntry = 0;
    study.renderEntry();
    return false;
};

study.renderPreviousEntry = function(e) {
    e.preventDefault();
    study.set_json.currentEntry -= 1;
    if (study.set_json.currentEntry == -1) study.set_json.currentEntry = study.set_json.entries.length - 1;
    study.renderEntry();
    return false;
};

study.showAnswer = function(e) {
    e.preventDefault();
    $('#studyViewContainerDiv').find('.study_hideMe').removeClass('hideMe');
    study.adjustHeight();
    var currentEntry = study.set_json.currentEntry;
    var d = study.set_json.entries[currentEntry];
    d.wrong = d.wrong + 1;
    if (currentEntry + 10 >= study.set_json.entries.length) {
	study.set_json.entries.push(d);
    } else {
	study.set_json.entries.splice(currentEntry + 10, 0,d);
    }
    $.ajax({'url': '/ajax/processShowAnswer.json', 'type': 'POST', 'dataType': 'json', 'data': d});
    return false;
};

study.renderSetEntries = function(json, textStatus) {
    json.currentEntry = 0;
    study.set_json = json;
    if (json.entries.length == 0) {
	if (json.contributor) {
	    if (study.social) {
		$('#studyViewContainerDiv').html('<p>This set has no entries.  Please go to canvas view to add entries for this set.</p>');
	    } else {
		$('#studyViewContainerDiv').html('<p>This set has no entries.  Please go to List View to add entries for this set.</p>');
	    }
	} else {
	    $('#studyViewContainerDiv').html('<p>This set has no entries.</p>');
	}
	return;
    }
    $('#studyViewContainerDiv').html(study.fetchTemplate('studyTableTemplate'));
    $('#show_answer').click(study.showAnswer);
    $('#next_entry').click(study.renderNextEntry);
    $('#previous_entry').click(study.renderPreviousEntry);
    if ((! study.social) || (study.socialView == 'canvas')) {
	if (json.contributor) {
	    $('#edit_entry').removeClass('hideMe').click(study.editEntry_studyView);
	    $('#add_entry').removeClass('hideMe').click(study.showAddEntryDiv_studyView);
	    $('#delete_entry').removeClass('hideMe').click(study.deleteEntry_studyView);
	}
	$('#entries_search_term').removeClass('hideMe');
	$('#entries_search_btn').removeClass('hideMe');
    }
    $('#entries_search_btn').click(study.entriesSearch_studyView);
    study.renderEntry();
};

study.deleteEntry_studyView = function(e) {
    e.preventDefault();
    var entryKey = $('#hidden_entryKey').text();
    $.ajax({'url': '/ajax/deleteentry.json', 'type': 'POST', 'dataType': 'json', data: {'entryKey': entryKey}});
    study.set_json.entries.splice(study.set_json.currentEntry,1);
    if (study.set_json.currentEntry == study.set_json.entries.length) {
	study.set_json.currentEntry = 0;
    }
    study.renderEntry();
    study.adjustHeight();
    return false;
};

study.hideEditEntryDiv_studyView = function() {
    $('#editEntryDiv').hide();
    study.removeEditors();
    $('#editEntryDiv').html('');
    $('#editEntryDiv').show();
    study.adjustHeight();
};

study.showAddEntryDiv_studyView = function(e) {
    e.preventDefault();
    study.hideEditEntryDiv_studyView();
    $('#addEntryDiv').html(study.fetchTemplate('addEntryTemplate'));
    study.addEditors();
    study.renderTagTable();
    $("input.submitbtn").click(study.addEntry_studyView);
    $('#addEntryDiv').scrollIntoView();
    study.adjustHeight();
    return false;
};

study.hideAddEntryDiv_studyView = function() {
    study.removeEditors();
    $('#addEntryDiv').html('');
    study.adjustHeight();
};

study.addEntry_studyView = function(e) {
    if ( $('#thelist').length == 0) {
	$('#relatedEntries').html(study.fetchTemplate('listViewTemplate_contributor'));
    }
    study.addEntry_listView(e);
    study.adjustHeight();
};

study.entriesSearch_studyView = function(e) {
    $('#entries_search_btn').val('Searching').disable();
    var searchTerm = $('#entries_search_term').val();
    var setKey = $('#hidden_setKey').text();
    var entryKey = $('#hidden_entryKey').text();
    var data = {'searchTerm': searchTerm, 'setKey': setKey, 'entryKey': entryKey};
    $('#relatedEntries').load('/ajax/entriesSearch.html',data,function(){
		$(".stripeMe tr").mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
		$(".stripeMe tr:nth-child(even)").addClass("alt");
		$("#thelist").click(study.listView_click);
		$('#thelist').dblclick(study.editEntry_dblclick);
		study.entryCount = $('#thelist').find('td.questionColumn').length;
		study.showOrHideEntryCount();
		$('#entries_search_btn').val('Search').enable();
		study.adjustHeight();
    });
};

study.addEntry_listView = function(e) {
    e.preventDefault();
    var question = study.getEditorContent('question');
    var answer = study.getEditorContent('answer');
    var setKey = $('#hidden_setKey').text();
    var tags = study.getSelectedTagsFromDOM();
    study.addEntry_saveSelectedTagsFromDOM();
    // save these for the purpose of updating the list view
    var data = {'question': question, 'answer': answer, 'setKey': setKey, 'tags': tags };
    $(this).attr('value','Processing').disable();
    $.ajax({'url': '/ajax/addentry.json', 'type': 'POST', 'dataType': 'json', 'async': false, 'data': data, 'success': study.addEntry_listView_success});
    return false;
}

study.showOrHideEntryCount = function() {
    if (study.entryCount == 1) {
	$('#entryCount').html('1 entry.');
	$('#entryCount').show();
    } else if (study.entryCount == 0) {
	$('#entryCount').hide();
    } else {
	$('#entryCount').html(study.entryCount + ' entries.');
	$('#entryCount').show();
    }
    study.adjustHeight();
};

study.shareOnFacebook_click = function(e) {
    e.preventDefault();
    var setKey = $('#hidden_setKey').text();
    u = location.protocol + '//' + location.hostname + '/share/set.html?setKey=' + setKey;
    var selectedOption = study.getSelectedOption('#setlist_select');
    t = selectedOption.text();
    window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer','toolbar=0,status=0,width=626,height=436');
    return false;
};

study.shareOnFacebook = function() {
    var setKey = $('#hidden_setKey').text();
    u = location.protocol + '//' + location.hostname + '/share/set.html?setKey=' + setKey;
    $('#shareURL_span').html('<a href="' + u + '">' + u + '</a>');
};

study.tinyMCE_init_instance_callback = function(inst) {
    // study.log('tinyMCE_init_instance_callback called');
};

study.tinyMCESettings = {
    mode: "textareas",
    theme: "advanced",
    format: "html",
    cleanup: true,
    tab_focus: ":prev,:next",
    plugins: "safari,style,table,advimage,advlink,inlinepopups,media,searchreplace,directionality,fullscreen",
    theme_advanced_buttons1 : "fullscreen,search,replace,undo,redo,ltr,rtl,code,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,link,unlink,image,sub,sup,formatselect,media,charmap",
    theme_advanced_buttons2 : "",
    theme_advanced_buttons3 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : true,
    
    template_external_list_url : "/tinymce/examples/lists/template_list.js",
    external_link_list_url : "/tinymce/examples/lists/link_list.js",
    external_image_list_url : "/tinymce/examples/lists/image_list.js",
    media_external_list_url : "/tinymce/examples/lists/media_list.js",
    init_instance_callback: 'study.tinyMCE_init_instance_callback'
};

$.ajaxSetup({'async': false});
//$.ajaxSetup({'async': false, 'beforeSend': study.removeEditors});
